package me.shan.search;

import org.junit.Assert;

/**
 * 描述：二分查找法
 *
 * @author liuchuang
 * @date 2021/6/14
 */
public class BinarySearch {

    /**
     * 搜索方法
     * @param array 入参有序数组，顺序从小到大
     * @return 返回值所在的位置，不存在时返回 -1
     */
    public static int search(int[] array, int value) {
        int left = 0, right = array.length - 1;
        int mid;
        while (left < right) {
            mid = left + ((right - left) >> 1);
            if (value == array[mid]) {
                return mid;
            } else if (value > array[mid]) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return value == array[left] ? left : -1;
    }

    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        Assert.assertEquals(6, search(array, 7));
    }

}
